package cn.cqie.attendance.manager.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.cqie.attendance.common.service.AttachmentService;
import cn.cqie.attendance.common.util.DateUtil;
import cn.cqie.attendance.common.util.Page;
import cn.cqie.attendance.manager.pojo.AdminAttendancePunch;
import cn.cqie.attendance.manager.pojo.AdminCourse;
import cn.cqie.attendance.manager.pojo.AdminStuCourseLeaves;
import cn.cqie.attendance.manager.service.AdminAttendanceService;
import cn.cqie.attendance.manager.util.ValidateRecordUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

@RestController
@Api(tags = "模板控制器")
public class TemplateController {

    @Value("${templateFilePath}")
    String templateFilePath;

    @Autowired
    AttachmentService attachmentService;

    @Autowired
    AdminAttendanceService adminAttendanceService;

    @GetMapping("/importTemplate")
    @ApiOperation("导入模板")
    public ResponseEntity<FileSystemResource> importTemplate() {
        return attachmentService.download(templateFilePath);
    }

    @PostMapping("/exportPunchRecord")
    @ApiOperation("导出打卡记录")
    @ApiImplicitParam(name = "punchRecordList", value = "打卡记录（直接返回页面上的数据集合即可）", required = true)
    public void exportPunchRecord(@RequestBody List<AdminAttendancePunch> punchRecordList, HttpServletResponse response) {
        Date date = new Date();
        String excelName = "record-" + DateUtil.formatDateToString("yyyyMMddHHmmssSSS", date)
                + (new Random().nextInt(10000));
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("门禁打卡记录", excelName),
                AdminAttendancePunch.class, punchRecordList);

        response.setHeader("Content-Disposition", "attachment;filename=" + excelName + ".xls");
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        try (BufferedOutputStream bufferedOutPut =
                     new BufferedOutputStream(response.getOutputStream())) {

            workbook.write(bufferedOutPut);
            bufferedOutPut.flush();
        } catch (IOException e) {
            System.out.println("发生异常");
        }
    }

    @PostMapping("/importPunchRecord")
    @ApiOperation("导入打卡记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "recordFile", value = "上传的文件(必须为Excel文件)", required = true),
            @ApiImplicitParam(name = "importMode", value = "上传文件重复记录的处理方式(0 终止 1 覆盖 2 跳过)", required = true)})
    public Page importPunchRecord(MultipartFile recordFile, Integer importMode) {
        return adminAttendanceService.importPunchRecord(recordFile, importMode);
    }

}
